﻿#include "write_log.hpp"
#include <chrono>
#include "time.hpp"
#include <filesystem>

#include "async_excutor.hpp"

namespace fs = std::filesystem;

std::vector<std::string>  write_log::getLogFiles(const std::string& directory)
{
	std::vector<std::string> logFiles;
	for (const auto& entry : fs::directory_iterator(directory))
	{
		if (entry.is_regular_file() && entry.path().extension() == ".log")
		{
			logFiles.push_back(entry.path().filename().string());
		}
	}
	return logFiles;
}

void write_log::init(string path) {
	path_ = path;
	async_exe_ = make_shared<AsyncExecutor>();
	async_exe_->start();
	async_exe_->excute([this]() {

		std::string folderPath = path_ + "/log";

		// 判断文件夹是否存在
		if (fs::exists(folderPath) && fs::is_directory(folderPath))
		{
			std::cout << "文件夹已存在：" << folderPath << std::endl;
		}
		else
		{
			// 创建文件夹
			if (fs::create_directory(folderPath))
			{
				std::cout << "文件夹创建成功：" << folderPath << std::endl;
			}
			else
			{
				std::cout << "文件夹创建失败：" << folderPath << std::endl;
				return;
			}
		}

		string log_path = path_ + "/log/" + utils_time::getCurrentSystemTime() + ".log";
		log_file_.open(log_path, std::ios::out | std::ios::app);
		
		clear_log();
	});

	
}

void write_log::log_out(const string& content) {
	async_exe_->excute([this](const string& str) {
		log_file_.write(str.c_str(), str.size());
		log_file_.flush();
	}, content);
	
}


void write_log::log_out(const string& level, const string& info)
{
	/*int timezone_offset = 8 * 3600;

	int64_t now = std::chrono::duration_cast<chrono::seconds>(std::chrono::system_clock::now().time_since_epoch()).count();
	
	string timeFormat = utils_time::time_format(now+ timezone_offset, "%H:%M:%S");*/


	std::time_t now = std::time(nullptr);
	std::tm* timeinfo = std::localtime(&now);

	// 获取毫秒
	auto milliseconds = std::chrono::duration_cast<std::chrono::milliseconds>(
		std::chrono::system_clock::now().time_since_epoch()
	).count() % 1000;

	// 格式化时间
	std::ostringstream oss;
	oss << std::put_time(timeinfo, "%Y-%m-%d %H:%M:%S") << ":"
		<< std::setfill('0') << std::setw(3) << milliseconds;

	string timeFormat= oss.str();

	string content = "[" + timeFormat + "][" + level +"]" + info+"\n";
	log_out(content);
}

void write_log::del_log(std::vector<std::string> &files)
{
	for (auto it : files)
	{
		fs::remove(path_ + "/log/" + it);
	}
}


void write_log::clear_log()
{
	auto now = std::chrono::system_clock::to_time_t(std::chrono::system_clock::now());
	int64_t cha = 3600 * 24 * 30 * 3;
	string path = path_ + "/log";
	auto fileList = getLogFiles(path);
	for (auto it : fileList)
	{
		struct tm ptm;
		memset(&ptm, 0, sizeof(tm));
		sscanf(it.c_str(), "%d-%d-%d", &ptm.tm_year, &ptm.tm_mon, &ptm.tm_mday);
		ptm.tm_year -= 1900;
		--ptm.tm_mon;
		auto ts = mktime(&ptm);

		if (now - ts > cha)
		{
			fs::remove(path_ + "/log/" + it);
		}


	}
}
